//
//  SXHomeViewController.swift
//  微博09项目
//
//  Created by mac on 15/9/1.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class SXHomeViewController: SXBaseViewController {
    ///微博列表数据模型
    private lazy var statusListViewModel = StatusListViewModel()
    ///Modal动画提供者
    private lazy var photoBrowserAnimator = PhotoBrowserAnimator()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if !UserAccountViewModel.shareUserAccount.userLogon{
            LoginView?.setupInfo(nil,message:"关注一些人，回这里看看有什么惊喜")
            return
        }
        // 注册通知
        /**
        1. 通知`名`
        2. 对象，监听`发送通知`的对象，如果是 nil，监听所有发送该通知的对象
        3. 队列，调度 block 的队列，如果是 nil，在主线程调度 block 执行
        4. block：接收到通知执行的方法
        
        * 目前 iOS 开发中，更多的人喜欢用 block，所有的代码写在一起！
        
        使用 通知的 block 有陷阱，只要使用 self. 一定会循环引用！
        */
        NSNotificationCenter.defaultCenter().addObserverForName(SXStatusPictureViewSelectedPhotoNotification, object: nil, queue: nil) { [weak self](notification) -> Void in
            guard let urls = notification.userInfo![SXStatusPictureViewSelectedPhotoURLsKey] as? [NSURL] else{
                return
            }
            guard let indexPath = notification.userInfo![SXStatusPictureViewSelectedPhotoIndexPathKey] as? NSIndexPath else {
                return
            }
            guard let picView = notification.object as? SXStatusPictureView else{
                return
            }

            let PhotoVC = PhotoBrowserViewController(urls: urls, indexPath: indexPath)
            
            //1，指定动画提供者 transitioning - 转场，从一个界面跳转到另外一个界面的动画效果
            PhotoVC.transitioningDelegate = self?.photoBrowserAnimator
            
            //2.指定modal 展现样式是自定义的
            PhotoVC.modalPresentationStyle = UIModalPresentationStyle.Custom
           
            //3.计算位置
            let fromRect = picView.screenRect(indexPath)
            let toRect = picView.fullScreenRect(indexPath)
            
            self?.photoBrowserAnimator.prepareAnimator(picView,fromRect: fromRect, toRect: toRect, url: urls[indexPath.item])
            
            self?.presentViewController(PhotoVC, animated: true, completion: nil)
        }
        
       prepareTableView()
       loadData()
       
    }
    deinit{
        print("通知销毁了")
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    private func prepareTableView(){
        //注册可重用cell
        tableView.registerClass(SXStatusForwardCell.self, forCellReuseIdentifier: SXStatusForwardCellID)
        tableView.registerClass(SXStatusNormalCell.self, forCellReuseIdentifier: SXStatusNormalCellID)
        tableView.estimatedRowHeight = 200
        //如果不需要自动计算行高，那么就不要设置行高为：UITableViewAutomaticDimension
        //tableView.rowHeight = UITableViewAutomaticDimension
        tableView.rowHeight = 300
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        //设置下拉控件
        refreshControl = SXRefreashControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
       
        //添加上拉控件
        tableView.tableFooterView = pullUpView
        //设置refreshControl 的背景颜色
      //  refreshControl?.tintColor = UIColor.clearColor()
        
    }
    //加载数据
    func loadData() {
        //beginRefreshing 只会播放刷新动画，不会加载数据
        //开始刷新
        refreshControl?.beginRefreshing()
         statusListViewModel.loadStatuses(isPullUpRefreash: pullUpView.isAnimating()).subscribeNext({ (result) -> Void in
            //TODO:
            let count = (result as! NSNumber).integerValue
            self.showPulldownTips(count)
            }, error: { (error) -> Void in
                print(error)
                //关闭刷新控件
               // self.refreshControl?.endRefreshing()
                self.endLoadData()
                SVProgressHUD.showErrorWithStatus("你的网络不给力")
            }) { () -> Void in
                //关闭刷新控件
               // self.refreshControl?.endRefreshing()
                self.endLoadData()
                //加载完成刷新数据
                self.tableView.reloadData()
        }

    }
    
    //下拉条数提示
    private func showPulldownTips(count:Int){
      
        let title = count == 0 ? "没有新微博" : "刷新到\(count) 条微博"
        let height: CGFloat = 44
        let rect = CGRect(x: 0, y: -2 * height, width: UIScreen.mainScreen().bounds.width, height: height)
        
        pulldownTipLabel.text = title
        pulldownTipLabel.frame = rect
        UIView.animateWithDuration(1.2, animations: { () -> Void in
            //下拉的时候改变height
            self.pulldownTipLabel.frame = CGRectOffset(rect, 0, 3 * height)
            }) { (_) -> Void in
                UIView.animateWithDuration(1.2){ () -> Void in
                    UIView.animateWithDuration(1.2) { self.pulldownTipLabel.frame = rect }
                }
        }
    }
    //MARK: - 懒加载控件
    
    /// 下拉提示标签
    private lazy var pulldownTipLabel:UILabel = {
        let label = UILabel(title: nil, color: UIColor.whiteColor(), fontSize: 18)
        
        label.backgroundColor = UIColor.orangeColor()
        label.textAlignment = NSTextAlignment.Center
        
        //添加Label到导航条上
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
       
        return label
    }()
    
    /// 结束刷新数据
    private func endLoadData(){
        //关闭刷新控件
        self.refreshControl?.endRefreshing()
        //关闭上拉刷新动画
        self.pullUpView.stopAnimating()
    }
    //懒加载：上拉控件
    private var pullUpView:UIActivityIndicatorView = {
        
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        indicator.color = UIColor.darkGrayColor()
       
        return indicator
    }()
    
}
//类似于OC的分类
extension SXHomeViewController{
     //数据行数
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      // return statusListViewModel.statuses?.count ?? 0
        print(statusListViewModel.statuses.count)
       return statusListViewModel.statuses.count
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
         let statusViewModel = statusListViewModel.statuses[indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier(statusViewModel.cellID, forIndexPath: indexPath) as! SXStatusCell
       
//        cell.textLabel?.text = status.text
            cell.statusViewModel = statusViewModel
        /// 添加上拉刷新
        if indexPath.row == (statusListViewModel.statuses.count - 1) && !pullUpView.isAnimating(){
            print("显示上拉视图")
            pullUpView.startAnimating()
            loadData()
        }
        return cell
    }
    //cell 的高度
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        //1，先拿到model数据
        let viewModel = statusListViewModel.statuses[indexPath.item]
        //2，获取当前的cell
        let cell = tableView.dequeueReusableCellWithIdentifier(viewModel.cellID) as! SXStatusCell
        //判断行高缓存了没有，如果缓存了，就直接返回
        if viewModel.rowHeight > 0{
            return viewModel.rowHeight
        }
        //如果行高没有被缓存，就给将当前的行高记录下来
       viewModel.rowHeight = cell.rowHeight(viewModel)

        //3，返回行高
        return viewModel.rowHeight
    }

}
